<?php

namespace Encore\Admin\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class TableToColumnCommand extends Command
{
    protected $signature = 'admin:cols {table} {--type=}';

    protected $description = '通过数据表生成指定字段样式 str array column comment gird show form json col';

    public function handle()
    {
        $table = $this->argument('table');
        $type = $this->options()['type'];

        if (!Schema::hasTable($table)) {
            $this->error("{$table} 表名不存在");

            return;
        }
        $columns = DB::select(/** @lang text */ 'SELECT column_name as col,column_comment as comment FROM information_schema.COLUMNS WHERE table_name = ? AND table_schema = ? order by ordinal_position', [$table, env('DB_DATABASE')]);
        $str = '';
        foreach ($columns as $column) {
            switch ($type) {
                case 'str':
                    $str .= "'{$column->col}',\n";
                    break;
                case 'array':
                    $str .= "'{$column->col}'=>'',\n";
                    break;
                case 'column':
                    $str .= "'{$column->col}'=>\$row[0],\n";
                    break;
                case 'comment':
                    $str .= "'{$column->col}'=>'{$column->comment}',\n";
                    break;
                case 'grid':
                    $str .= "\$grid->column('{$column->col}','{$column->comment}');\n";
                    break;
                case 'show':
                    $str .= "\$show->field('{$column->col}','{$column->comment}');\n";
                    break;
                case 'form':
                    $str .= "\$form->text('{$column->col}','{$column->comment}');\n";
                    break;
                case 'json':
                    $str .= "\"{$column->col}\":\"{$column->comment}\",\n";
                    break;
                case 'text':
                    $str .= ($column->comment ?: "-") . "\n";
                    break;
                case 'col':
                    $str .= $column->col . "\n";
                    break;
                default:
                    $str .= "'{$column->col}',";
            }
        }
        $this->info($str);
    }
}
